// 全局变量
let selectedFunctions = new Set();

// DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    // 历史记录按钮
    const historyBtn = document.getElementById('historyLink');
    if (historyBtn) {
        historyBtn.addEventListener('click', function(e) {
            e.preventDefault();
            showHistoryModal();
        });
    }
});

// 初始化应用
function initializeApp() {
    checkAuthentication();
    loadCarModels();
    loadFunctions();
    setupEventListeners();
    setupInputValidation();
    displayUserInfo();
}

// 设置事件监听器
function setupEventListeners() {
    // 文本域字符计数
    const inputText = document.getElementById('inputText');
    inputText.addEventListener('input', updateCharCount);
    inputText.addEventListener('keydown', function(e) {
        // 防止在达到最大长度时继续输入
        if (this.value.length >= 1424 && e.key !== 'Backspace' && e.key !== 'Delete' && e.key !== 'ArrowLeft' && e.key !== 'ArrowRight' && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') {
            e.preventDefault();
        }
    });
    
    // 生成按钮
    const generateBtn = document.getElementById('generateBtn');
    generateBtn.addEventListener('click', handleGenerate);
    
    // 清除按钮
    const clearBtn = document.getElementById('clearBtn');
    clearBtn.addEventListener('click', handleClear);
    
    // 登出按钮
    const logoutBtn = document.getElementById('logoutBtn');
    logoutBtn.addEventListener('click', handleLogout);
}

// 设置输入验证
function setupInputValidation() {
    const inputText = document.getElementById('inputText');
    const inputError = document.getElementById('inputError');
    const errorMessage = document.getElementById('errorMessage');
    
    inputText.addEventListener('blur', function() {
        const value = this.value.trim();
        if (value.length > 0 && value.length > 1424) {
            showError('输入内容长度不能超过1424位');
        } else {
            hideError();
        }
    });
    
    inputText.addEventListener('input', function() {
        const value = this.value.trim();
        if (value.length === 0 || value.length <= 1424) {
            hideError();
        }
    });
}

// 显示错误信息
function showError(message) {
    const inputError = document.getElementById('inputError');
    const errorMessage = document.getElementById('errorMessage');
    errorMessage.textContent = message;
    inputError.classList.remove('hidden');
}

// 隐藏错误信息
function hideError() {
    const inputError = document.getElementById('inputError');
    inputError.classList.add('hidden');
}

// 更新字符计数
function updateCharCount() {
    const inputText = document.getElementById('inputText');
    const charCount = document.getElementById('charCount');
    const length = inputText.value.length;
    charCount.textContent = `${length}/1424`;
    
    // 根据长度改变颜色
    if (length > 1424) {
        charCount.className = 'text-sm text-red-400';
    } else if (length > 0) {
        charCount.className = 'text-sm text-green-400';
    } else {
        charCount.className = 'text-sm text-gray-400';
    }
}

// 加载功能列表
async function loadFunctions() {
    try {
        const response = await fetch('/api/functions', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
        
        if (!response.ok) {
            if (response.status === 401) {
                // 认证失败，跳转到登录页
                window.location.href = '/login';
                return;
            }
            throw new Error(`HTTP ${response.status}`);
        }
        
        const data = await response.json();
        
        if (data.functions) {
            renderFunctionOptions(data.functions);
        }
    } catch (error) {
        console.error('加载功能列表失败:', error);
        showNotification('加载功能列表失败', 'error');
    }
}

// 渲染功能选项
function renderFunctionOptions(functions) {
    const container = document.getElementById('functionOptions');
    container.innerHTML = '';
    
    functions.forEach(function(func) {
        const option = document.createElement('div');
        option.className = 'function-option flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50';
        option.innerHTML = `
            <input type="checkbox" class="custom-checkbox mr-3" id="func_${func}" value="${func}">
            <label for="func_${func}" class="text-sm text-gray-700 cursor-pointer">${func}</label>
        `;
        
        // 添加点击事件
        option.addEventListener('click', function(e) {
            if (e.target.type !== 'checkbox') {
                const checkbox = this.querySelector('input[type="checkbox"]');
                checkbox.checked = !checkbox.checked;
                toggleFunction(checkbox);
            }
        });
        
        // 复选框变化事件
        const checkbox = option.querySelector('input[type="checkbox"]');
        checkbox.addEventListener('change', function() {
            toggleFunction(this);
        });
        
        container.appendChild(option);
    });
}

// 切换功能选择
function toggleFunction(checkbox) {
    const functionName = checkbox.value;
    const optionDiv = checkbox.closest('.function-option');
    
    if (checkbox.checked) {
        selectedFunctions.add(functionName);
        optionDiv.classList.add('selected');
    } else {
        selectedFunctions.delete(functionName);
        optionDiv.classList.remove('selected');
    }
}

// 处理生成请求
async function handleGenerate() {
    // 验证输入
    if (!validateForm()) {
        return;
    }
    
    // 显示加载状态
    showLoading(true);
    
    try {
        const formData = new FormData();
        formData.append('input_text', document.getElementById('inputText').value.trim());
        formData.append('car_model', document.getElementById('carModel').value);
        
        // 添加选中的功能
        selectedFunctions.forEach(func => {
            formData.append('functions', func);
        });
        
        const response = await fetch('/api/generate', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            },
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            displayResults(result.data);
            showNotification('生成成功！', 'success');
        } else {
            showNotification(result.message || '生成失败', 'error');
        }
    } catch (error) {
        console.error('生成失败:', error);
        showNotification('生成失败，请重试', 'error');
    } finally {
        showLoading(false);
    }
}

// 验证表单
function validateForm() {
    const inputText = document.getElementById('inputText').value.trim();
    const carModel = document.getElementById('carModel').value;
    
    // 验证输入文本
    if (!inputText) {
        showNotification('请输入内容', 'error');
        return false;
    }
    
    if (inputText.length > 1424) {
        showNotification('输入内容长度不能超过1424位', 'error');
        return false;
    }
    
    // 验证车型
    if (!carModel) {
        showNotification('请选择车型', 'error');
        return false;
    }
    
    // 验证功能选择
    if (selectedFunctions.size === 0) {
        showNotification('请至少选择一个功能', 'error');
        return false;
    }
    
    return true;
}

// 显示结果
function displayResults(data) {
    // 显示输出数字
    const outputNumber = document.getElementById('outputNumber');
    outputNumber.textContent = data.output_number || '--';
    outputNumber.classList.add('fade-in');
    
    // 显示二维码图片
    const qrImage = document.getElementById('qrImage');
    if (data.qr_code && data.qr_code !== 'base64_encoded_image_placeholder') {
        qrImage.innerHTML = `<img src="data:image/png;base64,${data.qr_code}" alt="二维码" class="max-w-full h-auto">`;
    } else {
        qrImage.innerHTML = `
            <div class="text-center">
                <div class="w-32 h-32 bg-gray-200 rounded-lg flex items-center justify-center mb-2">
                    <i class="fas fa-qrcode text-4xl text-gray-400"></i>
                </div>
                <p class="text-gray-600">二维码生成中...</p>
            </div>
        `;
    }
    qrImage.classList.add('fade-in');
}

// 处理清除请求
async function handleClear() {
    try {
        const response = await fetch('/api/clear', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            clearForm();
            showNotification('清除成功', 'success');
        } else {
            showNotification(result.message || '清除失败', 'error');
        }
    } catch (error) {
        console.error('清除失败:', error);
        showNotification('清除失败，请重试', 'error');
    }
}

// 清除表单
function clearForm() {
    // 清除文本域
    document.getElementById('inputText').value = '';
    updateCharCount();
    
    // 清除车型选择
    document.getElementById('carModel').value = '';
    
    // 清除功能选择
    selectedFunctions.clear();
    document.querySelectorAll('#functionOptions input[type="checkbox"]').forEach(checkbox => {
        checkbox.checked = false;
        checkbox.closest('.function-option').classList.remove('selected');
    });
    
    // 清除结果显示
    document.getElementById('outputNumber').textContent = '--';
    document.getElementById('qrImage').innerHTML = `
        <div class="text-gray-400 text-center">
            <i class="fas fa-qrcode text-4xl mb-2"></i>
            <p>等待生成二维码</p>
        </div>
    `;
    
    // 隐藏错误信息
    hideError();
}

// 显示/隐藏加载状态
function showLoading(show) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (show) {
        loadingOverlay.classList.remove('hidden');
    } else {
        loadingOverlay.classList.add('hidden');
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-x-full`;
    
    // 根据类型设置样式
    switch (type) {
        case 'success':
            notification.className += ' bg-green-500 text-white';
            break;
        case 'error':
            notification.className += ' bg-red-500 text-white';
            break;
        case 'warning':
            notification.className += ' bg-yellow-500 text-white';
            break;
        default:
            notification.className += ' bg-blue-500 text-white';
    }
    
    notification.innerHTML = `
        <div class="flex items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 检查认证状态
function checkAuthentication() {
    const token = localStorage.getItem('access_token');
    if (!token) {
        // 没有token，跳转到登录页
        window.location.href = '/login';
        return;
    }
    
    // 验证token
    fetch('/api/verify-token', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (!data.valid) {
            // token无效，清除本地存储并跳转到登录页
            localStorage.removeItem('access_token');
            localStorage.removeItem('username');
            window.location.href = '/login';
        }
    })
    .catch(() => {
        // 网络错误，清除本地存储并跳转到登录页
        localStorage.removeItem('access_token');
        localStorage.removeItem('username');
        window.location.href = '/login';
    });
}

// 显示用户信息
function displayUserInfo() {
    const username = localStorage.getItem('username');
    const isAdmin = localStorage.getItem('is_admin') === 'true';
    const userDisplayName = document.getElementById('userDisplayName');
    const adminLink = document.getElementById('adminLink');
    
    if (username) {
        const displayText = isAdmin ? `${username} (管理员)` : username;
        userDisplayName.textContent = displayText;
        
        // 如果是管理员，添加特殊样式和显示管理链接
        if (isAdmin) {
            userDisplayName.classList.add('text-blue-600', 'font-semibold');
            adminLink.classList.remove('hidden');
        }
    }
}

// 处理登出
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        // 清除本地存储
        localStorage.removeItem('access_token');
        localStorage.removeItem('username');
        localStorage.removeItem('is_admin');
        localStorage.removeItem('remember_me');
        
        // 跳转到登录页
        window.location.href = '/login';
    }
}

// 为API请求添加认证头
function getAuthHeaders() {
    const token = localStorage.getItem('access_token');
    return {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/x-www-form-urlencoded'
    };
} 

// 加载车型列表
async function loadCarModels() {
    try {
        const response = await fetch('/api/car-models', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
        if (!response.ok) {
            if (response.status === 401) {
                window.location.href = '/login';
                return;
            }
            throw new Error(`HTTP ${response.status}`);
        }
        const data = await response.json();
        const carModelSelect = document.getElementById('carModel');
        carModelSelect.innerHTML = '<option value="">请选择车型</option>';
        if (data.car_models) {
            data.car_models.forEach(model => {
                const opt = document.createElement('option');
                opt.value = model;
                opt.textContent = model;
                carModelSelect.appendChild(opt);
            });
        }
    } catch (error) {
        console.error('加载车型列表失败:', error);
        showNotification('加载车型列表失败', 'error');
    }
} 

async function showHistoryModal() {
    showLoading(true);
    try {
        const resp = await fetch('/api/history', {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }
        });
        const data = await resp.json();
        window._historyCache = data.history || [];
        let html = `<div id="historyModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-40">
            <div class="bg-white rounded-xl shadow-xl p-6 w-full max-w-2xl relative max-h-[90vh] overflow-y-auto">
                <button id="closeHistoryModal" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 text-xl">&times;</button>
                <h3 class="text-xl font-bold mb-4">历史记录（最近30条）</h3>
                <div class="overflow-x-auto">
                <table class="min-w-full text-xs md:text-sm text-gray-700">
                    <thead><tr>
                        <th class="px-2 py-1">日期</th>
                        <th class="px-2 py-1">车型</th>
                        <th class="px-2 py-1">功能</th>
                        <th class="px-2 py-1">输入</th>
                        <th class="px-2 py-1">输出</th>
                    </tr></thead>
                    <tbody>
                        ${(window._historyCache).map((r,i)=>`
                            <tr>
                                <td class="px-2 py-1 whitespace-nowrap">${r.created_at}</td>
                                <td class="px-2 py-1">${r.car_model}</td>
                                <td class="px-2 py-1">${r.functions.join(', ')}</td>
                                <td class="px-2 py-1 history-cell" style="max-width:120px;word-break:break-all;">
                                    ${truncateWithView(r.input_text, 40, '输入', i, 'input')}
                                </td>
                                <td class="px-2 py-1 history-cell" style="max-width:120px;word-break:break-all;">
                                    ${truncateWithView(r.output_number, 40, '输出', i, 'output')}
                                </td>
                            </tr>
                        `).join('') || '<tr><td colspan="5" class="text-center text-gray-400 py-4">暂无历史记录</td></tr>'}
                    </tbody>
                </table>
                </div>
            </div>
        </div>`;
        document.body.insertAdjacentHTML('beforeend', html);
        document.getElementById('closeHistoryModal').onclick = closeHistoryModal;
        // 绑定查看全部事件
        document.querySelectorAll('.history-viewall').forEach(btn => {
            btn.onclick = function() {
                const idx = this.getAttribute('data-idx');
                const type = this.getAttribute('data-type');
                let val = '';
                if (window._historyCache && window._historyCache[idx]) {
                    val = type === 'input' ? window._historyCache[idx].input_text : window._historyCache[idx].output_number;
                }
                closeHistoryModal();
                showFullTextModal(type==='input'?'输入内容':'输出内容', val);
            };
        });
    } catch (e) {
        showNotification('加载历史失败', 'error');
    } finally {
        showLoading(false);
    }
}
function truncateWithView(str, len, label, idx, type) {
    if (!str) return '';
    if (str.length <= len) return `<span class="break-all">${escapeHtml(str)}</span>`;
    return `<span class="inline-block max-w-xs truncate align-bottom">${escapeHtml(str.slice(0,len))}...</span> <a href="javascript:void(0);" class="text-blue-500 underline history-viewall" data-idx="${idx}" data-type="${type}">查看全部</a>`;
}
function escapeHtml(str) {
    return String(str).replace(/[&<>"']/g, function(s) {
        return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[s];
    });
}
function showFullTextModal(title, content) {
    closeFullTextModal();
    let html = `<div id="fullTextModal" class="fixed inset-0 z-60 flex items-center justify-center bg-black bg-opacity-40">
        <div class="bg-white rounded-xl shadow-xl p-6 w-full max-w-lg relative">
            <button id="closeFullTextModal" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 text-xl">&times;</button>
            <h3 class="text-lg font-bold mb-4">${title}</h3>
            <pre class="w-full p-2 border rounded bg-gray-50 text-xs break-all max-h-80 overflow-auto whitespace-pre-wrap" style="font-family:inherit;">${escapeHtml(content)}</pre>
            <button id="copyFullTextBtn" class="mt-4 w-full bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded text-base font-semibold">复制全部</button>
        </div>
    </div>`;
    document.body.insertAdjacentHTML('beforeend', html);
    document.getElementById('closeFullTextModal').onclick = closeFullTextModal;
    document.getElementById('copyFullTextBtn').onclick = function() {
        navigator.clipboard.writeText(content);
        showNotification('已复制到剪贴板','success');
    };
}
function closeFullTextModal() {
    const modal = document.getElementById('fullTextModal');
    if (modal) modal.remove();
} 
function closeHistoryModal() {
    const modal = document.getElementById('historyModal');
    if (modal) modal.remove();
} 